<!--  -->
<template>
  <div class="">
    <a-card :bordered="false" class="search-wrapper">
      <div class="search-box">
        <a-tabs v-model="tabActive" :style="{ height: '50px' }" @tabClick="typeClick">
          <a-tab-pane v-for="(item, index) in tabList" :key="index" :tab="item.name"></a-tab-pane>
        </a-tabs>
      </div>
      <div class="search-form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24" v-if="tabActive == 0">
              <a-form-item>
                <DateTimeRange
                  v-model="filter._dateRange"
                  :startDate.sync="filter.beginTime"
                  :endDate.sync="filter.endTime"
                  allowClear
                  :placeholder="['生成开始时间', '生成结束时间']"
                />
              </a-form-item>
            </a-col>
            <template v-else>
              <a-col :md="6" :sm="24">
                <a-form-item>
                  <DateTimeRange
                    v-model="filter._auditDateRange"
                    :startDate.sync="filter.auditBeginTime"
                    :endDate.sync="filter.auditEndTime"
                    allowClear
                    :placeholder="['审核开始时间', '审核结束时间']"
                  />
                </a-form-item>
              </a-col>
              <!-- <a-col :md="6" :sm="24">
                <a-form-item>
                  <a-input v-model="filter.receivableName" placeholder="分账接收方" />
                </a-form-item>
              </a-col> -->
            </template>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <project-select v-model="filter.projectCode" placeholder="投资项目" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <brand-select v-model="filter.brandCode" placeholder="分账品牌" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <store-select v-model="filter.storeCode" placeholder="分账店铺" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <!-- <DateTimeRange
                  v-model="filter._dateRange"
                  :startDate.sync="filter.transBeginDate"
                  :endDate.sync="filter.transEndDate"
                  :placeholder="['交易开始时间', '交易结束时间']"
                /> -->
                <a-date-picker
                  v-model="filter.transDate"
                  placeholder="交易时间"
                  valueFormat="YYYY-MM-DD"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <template v-if="tabActive == 1">
              <a-col :md="6" :sm="24">
                <a-form-item>
                  <a-select v-model="filter.remitStatus" placeholder="划账状态" style="width: 100%">
                    <a-select-option value="0"> 待处理 </a-select-option>
                    <a-select-option value="1"> 已完成 </a-select-option>
                    <a-select-option value="2"> 处理中 </a-select-option>
                    <a-select-option value="9"> 失败 </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item>
                  <DateTimeRange
                    v-model="filter._finishDateRange"
                    :startDate.sync="filter.finishBeginTime"
                    :endDate.sync="filter.finishEndTime"
                    :placeholder="['划账开始时间', '划账结束时间']"
                  />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="8" :sm="24">
              <a-input-group compact>
                <a-select v-model="filter.accountType" placeholder="请选择分账接收方类型" style="width:50%">
                  <a-select-option value="1"> 资方分账账户 </a-select-option>
                  <a-select-option value="2"> 平台分账账户 </a-select-option>
                  <a-select-option value="3"> 其他分账账户 </a-select-option>
                </a-select>
                <a-input style="width: 50%" placeholder="分账接收方名称" v-model="filter.receivableName" />
              </a-input-group>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handle">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (filter = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card class="table-wrapper">
      <div class="box">
        <div class="box-act">
          <a-button size="small" @click="batchConfirmRemitHandler" v-if="tabActive == 0&&userInfo.identityType==='1'">
            确认划账
          </a-button>
        </div>
      </div>
      <a-table
        :loading="tableLoading"
        bordered
        :columns="tabActive == 0 ? auditColumns : approvedColumns"
        :pagination="pagination"
        :data-source="tableData || []"
        @change="(e) => handle(e)"
        :scroll="{ y: tableHeight, x: 'max-content' }"
        :row-selection="
          tabActive == 0 && userInfo.identityType==='1' ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange } : null
        "
      >
        <span slot="receivableAccount" slot-scope="text, record">
         <div class="text"> {{text}} </div>（{{ record.receivableAccount }}）
        </span>
        <span slot="projectCode" slot-scope="text, record">
         <div class="text"> {{text}} </div>（{{ record.projectCode }}）
        </span>
        <span slot="brandCode" slot-scope="text, record">
         <div class="text"> {{text}} </div>（{{ record.brandCode }}）
        </span>
        <span slot="storeCode" slot-scope="text, record">
         <div class="text"> {{text}} </div>（{{ record.storeCode }}）
        </span>
        <span slot="action" slot-scope="text, record" v-if="userInfo.identityType==='1'">
          <a-button type="link" @click="confirmRemitHandler(record)">确认划账</a-button>
        </span>
      </a-table>
    </a-card>
    <!-- <setup-brand ref="setup-brand" /> -->
  </div>
</template>

<script>
import { divideAccountDetail, divideAccountComfirm } from '@/api/subject'
import { DateTimeRange } from '@/components'
// import ProjectForm from './module/project-form'
// import ProjectProgress from './module/project-progress'
import GoTask from '@/components/goTask'
// import moment from 'moment'
import { mapState } from "vuex"
import setupBrand from './module/setup-brand'
import ProjectSelect from '@/myComponents/project-select.vue'
import BrandSelect from '@/myComponents/brand-select.vue'
import StoreSelect from '@/myComponents/store-select'
import { digitSymbolFormat } from '@/utils/index'
// const startTime = moment().subtract(3, 'days').format('YYYY-MM-DD 00:00:00')
// const endTime = moment().format('YYYY-MM-DD 23:59:59')
const auditColumns = [
  { title: '生成时间', dataIndex: 'createTime' },
  {
    title: '分账接收方及账户',
    dataIndex: 'receivableName',
    scopedSlots: { customRender: 'receivableAccount' }
  },
  { title: '投资项目', dataIndex: 'projectName', scopedSlots: { customRender: 'projectCode' } },
  {
    title: '分账比例(万分之)',
    dataIndex: 'divideRadio'
  },
  {
    title: '分账金额(元)',
    dataIndex: 'divideAmount',
    customRender: (text) => digitSymbolFormat(text)
  },
  { title: '分账品牌', dataIndex: 'brandName', scopedSlots: { customRender: 'brandCode' } },
  { title: '分账店铺', dataIndex: 'storeName', scopedSlots: { customRender: 'storeCode' } },
  {
    title: '营业收入(元)',
    dataIndex: 'incomeAmount',
    customRender: (text) => digitSymbolFormat(text)
  },
  { title: '交易日期', dataIndex: 'transDate' },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const approvedColumns = [
  { title: '审核时间', dataIndex: 'auditTime', scopedSlots: { customRender: 'menuName' } },
  { title: '生成时间', dataIndex: 'createTime' },
  {
    title: '分账接收方及账户',
    dataIndex: 'receivableName',
    scopedSlots: { customRender: 'receivableAccount' }
  },
  { title: '投资项目', dataIndex: 'projectName', scopedSlots: { customRender: 'projectCode' } },
  {
    title: '分账比例(万分之)',
    dataIndex: 'divideRadio',
  },
  {
    title: '分账金额（元）',
    dataIndex: 'divideAmount',
    customRender: (text) => digitSymbolFormat(text)
  },
  { title: '划账状态', dataIndex: 'remitStatusDesc' },
  { title: '划账完成时间', dataIndex: 'receivableTime' },
  { title: '分账品牌', dataIndex: 'brandName', scopedSlots: { customRender: 'brandCode' } },
  { title: '分账店铺', dataIndex: 'storeName', scopedSlots: { customRender: 'storeCode' } },
  {
    title: '营业收入(元)',
    dataIndex: 'incomeAmount',
    customRender: (text) => digitSymbolFormat(text)
  },
  { title: '交易日期', dataIndex: 'transDate' }
]
export default {
  data() {
    return {
      tabActive: 0,
      tableLoading: false,
      filter: {
        pageSize: 10,
        pageNum: 1,
        beginTime: '',
        endTime: '',
        transDate: '',
        storeCode: undefined,
        auditBeginTime: '',
        auditEndTime: '',
        finishBeginTime: '',
        finishEndTime: '',
        receivableName: '',
        remitStatus: undefined,
        _dateRange: [],
        _auditDateRange: [],
        _finishDateRange: [],
        auditStatus: '0' // 待审核分账明细  审核通过分账明细1
      },
      tableData: [],
      pagination: {
        current: 1,
        'show-size-changer': true,
        total: 0
      },
      approvedColumns,
      auditColumns,
      selectedRowKeys: [],
      selectedRows: [],
      tabList: [
        { name: '待审核分账明细', value: 0 },
        { name: '审核通过分账明细', value: 1 }
      ]
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    tableHeight() {
      return document.body.clientHeight - this.tabbarHeight
    },
    ...mapState({
      userInfo: (state) => state.user.info
    })
  },
  components: {
    GoTask,
    DateTimeRange,
    setupBrand,
    ProjectSelect,
    BrandSelect,
    StoreSelect
    // ProjectForm,
    // ProjectProgress
  },
  activated() {
    const queryRoute = this.$route.query
    if (queryRoute.viewState) {
      const find = this.tabList.findIndex((v) => v.value == queryRoute.viewState)
      this.filter.auditStatus = queryRoute.viewState
      this.tabActive = find
    } else if (queryRoute.record) {
      const record = JSON.parse(queryRoute.record)
      this.filter.storeDailyRevenueId = record.id
      this.filter.storeCode = record.storeCode
      this.filter.transDate = record.transDate
    } else {
      this.filter.storeDailyRevenueId = ''
      this.filter.storeCode = undefined
      this.filter.transDate = ''
    }
    this.handle()
  },
  mounted() {
    const queryRoute = this.$route.query
    if (queryRoute.viewState) {
      const find = this.tabList.findIndex((v) => v.value == queryRoute.viewState)
      this.filter.auditStatus = queryRoute.viewState
      this.tabActive = find
    } else if (queryRoute.record) {
      const record = JSON.parse(queryRoute.record)
      this.filter.storeDailyRevenueId = record.id
      this.filter.storeCode = record.storeCode
      this.filter.transDate = record.transDate
    } else {
      this.filter.storeDailyRevenueId = ''
      this.filter.storeCode = undefined
      this.filter.transDate = ''
    }
    this.handle()
  },
  methods: {
    batchConfirmRemitHandler() {
      if (this.selectedRows.length) {
        const record = {
          ids: this.selectedRows.map((v) => v.id)
        }
        this.confirmRemitHandler(record)
      } else {
        this.$notification['error']({
          message: '错误提示',
          description: '请选择批量确认划账数据'
        })
      }
    },
    confirmRemitHandler(record) {
      const vm = this
      this.$confirm({
        title: '确认划账',
        content: '确认是否确认划账',
        class: 'confirm-box',
        onOk() {
          return new Promise((resolve, reject) => {
            divideAccountComfirm({ ids: record.id ? [record.id] : record.ids })
              .then(() => {
                vm.$notification['success']({
                  message: '成功提示',
                  description: '确认划账成功'
                })
                vm.handle()
                vm.selectedRowKeys = []
                vm.selectedRows = []
                resolve()
              })
              .catch(() => {
                return reject(new Error(''))
              })
          })
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    typeClick(index) {
      if (this.tabActive != index) {
        this.tabActive = index
        this.filter.auditStatus = this.tabList[index].value
        this.handle()
      }
    },
    addHandler() {
      this.$refs['project-form'].open()
    },
    editHandler(record) {
      this.$refs['project-form'].open(record)
    },
    brandHandler(record) {
      this.$refs['setup-brand'].open(record)
    },
    handle(v) {
      if (v && v.current) {
        if (this.filter.pageSize == v.pageSize) {
          this.pagination.current = v.current
          this.filter.pageNum = v.current
        } else {
          this.filter.pageSize = v.pageSize
          this.filter.pageNum = 1
          this.pagination.current = 1
        }
      } else {
        this.filter.pageNum = 1
        this.filter.pageSize = 10
        this.pagination.current = 1
      }
      this.tableLoading = true
      divideAccountDetail(this.filter)
        .then((res) => {
          this.tableLoading = false
          this.tableData = res.rows
          this.pagination.total = res.total || 0
        })
        .catch(() => {
          this.tableLoading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.box-act {
  display: flex;
}
.search-box {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  min-height: 47px;
  margin-bottom: 19px;
  .type-list {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    .type-item {
      height: 45px;
      line-height: 45px;
      border-bottom: 2px solid #fff;
      padding: 0 20px;
      font-size: 14px;
      cursor: pointer;
    }
    .type-item.active {
      border-bottom: 2px solid #4393f2;
      font-size: 16px;
      font-weight: 500;
      color: #4393f2;
    }
  }
}
.box-total-item {
  font-size: 12px;
}
</style>
